package com.sysmanagment.utiil.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Validator;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.faces.FacesMessages;

import com.sysmanagment.dao.user.UserDAO;
import com.sysmanagment.model.user.User;

@Name("usernameExistenceValidator")
@BypassInterceptors
@Validator
public class ValidateUsernameExistence implements
		javax.faces.validator.Validator {

	

	@Override
	public void validate(FacesContext facesContext, UIComponent uiComponent,
			Object o) throws ValidatorException {
		
		boolean usernameExists = usernameExists((String) o);
		if (usernameExists) {
			throw new ValidatorException(FacesMessages.createFacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"snet.validator.usernameExists",
					"#{messages['snet.validator.usernameExists']}", o));
		}
	}

	protected boolean usernameExists(String username) {
		UserDAO userDAO= (UserDAO) Component.getInstance("userDAO");
		if (username != null) {
			User user = userDAO.getUser(username);

			if (user != null) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

}
